import axios from 'axios'
import { getToken } from '@/libs/cookie'
import { Message } from 'view-design'
import store from '@/store'

const HttpRequest = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
  headers: { 'Content-Type': 'application/json; charset=utf-8' }
})

HttpRequest.interceptors.request.use(
  config => {
    let token = getToken()
    if (token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

HttpRequest.interceptors.response.use(
  response => {
    const { code, data, message } = response.data
    if (code !== 200) {
      Message.error({
        content: message || 'Error',
        duration: 5
      })
      if (code === 401 || code === 403) {
        store.dispatch('handleResetToken').then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(message || 'Error')).catch((err) => {
        console.log(err)
      })
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)
    Message.error({
      content: error.message,
      duration: 5
    })
    return Promise.reject(error)
  }
)

export default HttpRequest
